import router from '@/router/index'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { useUserStore } from '@/store/modules/user'
import { useSettingStore } from '@/store/modules/setting'
// import { usePermissionStore } from '@/store/modules/permission'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/auth-redirect', '/shareDetail'] // 设置白名单
// 记录路由
// const hasRoles = true

router.beforeEach(async(to, from, next) => {
  // 开启进度条
  NProgress.start()
  // 设置标题
  if (typeof (to.meta.title) === 'string') {
    document.title = to.meta.title || 'vue-h5-perfect'
  }

  const UserStore = useUserStore()
  const SettingStore = useSettingStore()
  // 确定用户是否已登录过，存在Token
  const hasToken = UserStore.token
  if (hasToken) {
    if (to.path === '/login') {
      // 如果已登录，请重定向到主页
      next({ path: '/' })
    } else {
      // 授权

      SettingStore.isCollapse = false
      next()
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})

